const { Task, UserTask, User } = require('../models');
const { Op } = require('sequelize');

class TaskService {
    async getAvailableTasks() {
        return await Task.findAll({
            where: {
                isActive: true
            }
        });
    }

    async startTask(userId, taskId) {
        const task = await Task.findByPk(taskId);
        if (!task || !task.isActive) {
            throw new Error('Task not found or inactive');
        }

        // 检查是否已经接受了该任务
        const existingTask = await UserTask.findOne({
            where: {
                userId,
                taskId,
                status: {
                    [Op.in]: ['pending', 'in_progress']
                }
            }
        });

        if (existingTask) {
            throw new Error('Task already accepted');
        }

        // 创建新的用户任务
        const userTask = await UserTask.create({
            userId,
            taskId,
            status: 'in_progress',
            progress: 0
        });

        // 构建返回数据
        const taskData = {
            id: task.id,
            userTaskId: userTask.id,
            title: task.title,
            description: task.description,
            type: task.type,
            difficulty: task.difficulty,
            status: 'in_progress',
            progress: 0,
            reward: task.reward,
            createdAt: userTask.createdAt
        };

        // 确保 reward 是 JSON 对象
        if (typeof taskData.reward === 'string') {
            try {
                taskData.reward = JSON.parse(taskData.reward);
            } catch (e) {
                console.error('Failed to parse reward JSON:', e);
                taskData.reward = { experience: 0 };
            }
        }

        return taskData;
    }

    async makeChoice(userId, userTaskId, choiceIndex) {
        const userTask = await UserTask.findOne({
            where: {
                id: userTaskId,
                userId
            },
            include: [Task]
        });

        if (!userTask) {
            throw new Error('UserTask not found');
        }

        if (userTask.status !== 'in_progress') {
            throw new Error('Task is not in progress');
        }

        const task = userTask.Task;
        const choices = task.choices?.options || [];
        
        if (choiceIndex < 0 || choiceIndex >= choices.length) {
            throw new Error('Invalid choice index');
        }

        // 更新任务进度
        await userTask.update({
            status: 'completed',
            completedAt: new Date()
        });

        // 发放奖励
        const user = await User.findByPk(userId);
        const reward = task.reward;
        
        await user.update({
            experience: user.experience + (reward.experience || 0)
        });

        return {
            message: '选择成功',
            choice: choices[choiceIndex],
            reward
        };
    }

    // 获取用户当前进行中的任务
    async getUserTasks(userId) {
        // 获取用户所有相关任务记录
        const userTaskRecords = await UserTask.findAll({
            where: {
                userId,
                status: {
                    [Op.in]: ['pending', 'in_progress', 'completed']
                }
            },
            include: [{
                model: Task,
                as: 'task',
                where: {
                    isActive: true
                },
                attributes: ['id', 'title', 'description', 'type', 'difficulty', 'reward']
            }],
            order: [['createdAt', 'DESC']]
        });

        // 格式化任务数据
        return userTaskRecords.map(userTask => {
            const taskData = {
                id: userTask.taskId,
                userTaskId: userTask.id,
                title: userTask.task.title,
                description: userTask.task.description,
                type: userTask.task.type,
                difficulty: userTask.task.difficulty,
                status: userTask.status,
                progress: userTask.progress,
                reward: userTask.task.reward,
                createdAt: userTask.createdAt,
                completedAt: userTask.completedAt
            };

            // 确保 reward 是 JSON 对象
            if (typeof taskData.reward === 'string') {
                try {
                    taskData.reward = JSON.parse(taskData.reward);
                } catch (e) {
                    console.error('Failed to parse reward JSON:', e);
                    taskData.reward = { experience: 0, coins: 0 };
                }
            }

            return taskData;
        });
    }

    // 获取用户已完成的任务
    async getCompletedTasks(userId) {
        return await UserTask.findAll({
            where: {
                userId,
                status: 'completed'
            },
            include: [Task]
        });
    }
}

module.exports = new TaskService();